package com.example.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
        Object username = httpServletRequest.getSession().getAttribute("user");
        //获取Servlet请求路径
        String servletPath = httpServletRequest.getServletPath();
        if(!servletPath.contains("login")&&null==username){
            //若没有登录 则回到登录界面
            httpServletRequest.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
        }else{
            //若已经登录 则放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
